package com.lz.helper.idcard

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.lz.helper.HelperConfig
import java.lang.ref.WeakReference

//指纹识别
class FingerHelper(
    context: Context,
    matcher: ByteArray,
    threshold: Float,
    callback: FingerCallback,
    factory: FingerRequest.Factory = DefFactory()
) : Handler(Looper.getMainLooper()), FingerRequest.FingerHandler {


    companion object {
        private const val MSG_OPEN = 1
        private const val MSG_RESULT = 2
        private const val MSG_ERR = 3
    }

    //核心处理
    private val request by lazy { factory.create(context.applicationContext, matcher, threshold, this) }

    //回调
    private val reference = WeakReference(callback)

    //线程是否开启
    private var hasStarted = false

    fun start() {
        if (!hasStarted) {
            hasStarted = true
            Thread(request, "IDCardRequest-Thread").start()
        }
    }

    fun restart() {
        if (hasStarted) request.restart()
    }

    fun pause() {
        request.pause()
    }

    fun quit() {
        request.quit()
    }

    override fun handleMessage(msg: Message) {
        when (msg.what) {
            MSG_OPEN -> reference.get()?.onFingerOpened()
            MSG_ERR -> reference.get()?.onFingerError(msg.obj as Int)
            MSG_RESULT -> reference.get()?.onFingerResult(msg.obj as Int)
        }
    }

    override fun sendFingerOpenSuccess() {
        sendEmptyMessage(MSG_OPEN)
    }

    override fun sendFingerError(error: Int) {
        sendMessage(obtainMessage(MSG_ERR, error))
    }

    override fun sendFingerResult(threshold: Int) {
        sendMessage(obtainMessage(MSG_RESULT, threshold))
    }

    interface FingerCallback {

        //打开成功
        fun onFingerOpened()

        //失败系列
        fun onFingerError(error: Int)

        //匹配结果
        fun onFingerResult(threshold: Int)
    }

    class DefFactory : FingerRequest.Factory {

        override fun create(
            context: Context,
            matcher: ByteArray,
            threshold: Float,
            handler: FingerRequest.FingerHandler
        ): FingerRequest {
            return when (HelperConfig.flatNum()) {
                17 -> NxsFingerRequest(context, matcher, threshold, handler) //新像素
                else -> UFingerRequest(context, matcher, threshold, handler)//老像素, 辽源通达串,U
            }
        }
    }
}